/*
 * FormAberturaComanda.java
 *
 * Created on 05/05/2013, 23:27:14
 */
package forms;

import classes.Conexao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jonatas
 */
public class FormAberturaComanda extends javax.swing.JInternalFrame {

    /**
     * Creates new form FormAberturaComanda
     */
    public FormAberturaComanda() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabelComanda = new javax.swing.JLabel();
        jButtonAbrir = new javax.swing.JButton();
        jComboBoxComanda = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableComanda = new javax.swing.JTable();

        setClosable(true);
        setIconifiable(true);
        setTitle("Abertura de Comanda");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener()
        {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt)
            {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt)
            {
                formInternalFrameOpened(evt);
            }
        });

        jLabelComanda.setText("Comanda:");

        jButtonAbrir.setText("Abrir");
        jButtonAbrir.setToolTipText("Clique aqui para abrir");
        jButtonAbrir.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonAbrirActionPerformed(evt);
            }
        });

        jComboBoxComanda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTableComanda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {

            },
            new String []
            {
                "Comandas em Uso", "Data e Hora de Abertura"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean []
            {
                false, false
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex)
            {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableComanda);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelComanda)
                        .addGap(8, 8, 8)
                        .addComponent(jComboBoxComanda, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelComanda)
                    .addComponent(jComboBoxComanda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonAbrir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-396)/2, (screenSize.height-307)/2, 396, 307);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAbrirActionPerformed
        //Pega o numero da comanda e converte para int
        int c = Integer.parseInt(jComboBoxComanda.getSelectedItem().toString());
        //Pega a hora do sistema para inserir no banco
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        System.out.println(sdf.format(new Date()));
        
        try {

            String sql = "INSERT INTO snooker.\"ABERTURA_COMANDA\" "
                    + "VALUES (abertura_comanda_seq.nextval,sysdate,null," + c + ")";

            if (Conexao.atualizar(sql) == -1) {
                JOptionPane.showMessageDialog(null, Conexao.getErro(), "Cadastro", 1);
            } 
            pesquisarTudo();
            atualizarTabela();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro:\n" + e.getMessage(), "Erro!", 0);
        }
    }//GEN-LAST:event_jButtonAbrirActionPerformed

    //Executa essas instruções ao abrir o internalFrame
    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened

        try {
            pesquisarTudo();
            atualizarTabela();
        } 
        catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage(), "Erro!", 0);
        }
    }//GEN-LAST:event_formInternalFrameOpened

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt)//GEN-FIRST:event_formInternalFrameActivated
    {//GEN-HEADEREND:event_formInternalFrameActivated
        try {
            pesquisarTudo();
            atualizarTabela();
        }
        catch(SQLException e) {
            JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage(), "Erro!", 0);
        }
    }//GEN-LAST:event_formInternalFrameActivated
    private void pesquisarTudo()
    {
        DefaultComboBoxModel modelo = (DefaultComboBoxModel) jComboBoxComanda.getModel();
        modelo.removeAllElements();//para cada vez que executar isso, limpar as linhas da tabela

        try
        {
            String sql = "select * from COMANDA where \"cd_comanda\" not in"
                    + "(select \"cd_comanda\" from ABERTURA_COMANDA where \"dt_hora_fechar\" is null) "
                    + "AND \"ic_ativa_inativa\" = 'S' ORDER BY \"cd_comanda\"";

            ResultSet res = Conexao.consultar(sql);

            if (Conexao.consultar(sql) == null) {
                JOptionPane.showMessageDialog(null, "Erro na consulta:\n" + Conexao.getErro(), "Erro!", 0);
            }
            else
            {
                if (Conexao.consultar(sql).next())
                {
                    while (res.next())
                    {
                        modelo.addElement(
                                res.getInt("cd_comanda"));
                    }
                    jButtonAbrir.setEnabled(true);
                    jComboBoxComanda.setEnabled(true);
                    jButtonAbrir.setToolTipText("Clique aqui para abrir a comanda.");
                }
                else
                {
                    jButtonAbrir.setEnabled(false);
                    jComboBoxComanda.setEnabled(false);
                    jButtonAbrir.setToolTipText("Não há mais comandas cadastradas ou ativas.");
                }
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Erro na consulta: \n" + e.getMessage(), "Erro!", 0);
        }
    }

    private void atualizarTabela() throws SQLException {
        DefaultTableModel tableModel = (DefaultTableModel) jTableComanda.getModel();
        tableModel.setRowCount(0);

        String sqlAbertComa =
                "SELECT * FROM snooker.\"ABERTURA_COMANDA\" "
                + "WHERE \"ABERTURA_COMANDA\".\"dt_hora_fechar\" is null "
                + "ORDER BY \"ABERTURA_COMANDA\".\"cd_comanda\"";

        ResultSet rs1 = Conexao.consultar(sqlAbertComa);
        int comanda = 0;
        
        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        //System.out.println("Teste formato data: " + dt.format(new Date()));
        while (rs1.next()) {
            tableModel.addRow(new Object[]{
                        comanda = rs1.getInt("cd_comanda"),
                        dt.format( rs1.getTimestamp("dt_hora_abertura"))
                    });
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAbrir;
    private javax.swing.JComboBox jComboBoxComanda;
    private javax.swing.JLabel jLabelComanda;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableComanda;
    // End of variables declaration//GEN-END:variables
}
